iT邦幫忙

2024 iThome 鐵人賽

DAY 8
0
Software Development

LSTM結合Yolo v8對於多隻斑馬魚行為分析系列 第 8

day 8 yolo 辨識網球是否界內球系統

  • 分享至 

  • xImage
  •  

今天是第八天,最近流行奧運網遊賽事,因此我想寫一個網球yolo辨識系統,以下是程式碼

import cv2
import numpy as np
from ultralytics import YOLO  # 確保你已安裝 YOLOv8

# 載入訓練好的 YOLO 模型
model = YOLO('best.pt')  # 你應該替換成你自己訓練的模型權重

# 定義網球場地的邊界(這裡使用範例數據,應根據實際場地來調整)
court_boundaries = {
    'left': 100,
    'right': 500,
    'top': 50,
    'bottom': 400
}

def is_ball_in_bounds(ball_bbox, boundaries):
    x_center = (ball_bbox[0] + ball_bbox[2]) / 2
    y_center = (ball_bbox[1] + ball_bbox[3]) / 2
    
    if boundaries['left'] <= x_center <= boundaries['right'] and boundaries['top'] <= y_center <= boundaries['bottom']:
        return True
    else:
        return False

def process_image(image_path):
    # 讀取影像
    image = cv2.imread(image_path)

    # 使用 YOLO 模型進行推論
    results = model.predict(source=image)

    for result in results[0].boxes:
        bbox = result.xyxy[0].cpu().numpy()  # 取得邊界框 (x1, y1, x2, y2)
        label = result.cls[0].cpu().numpy()  # 取得類別
        score = result.conf[0].cpu().numpy()  # 取得信心分數

        # 假設類別 0 是網球(根據你訓練時的設定)
        if label == 0:  
            if is_ball_in_bounds(bbox, court_boundaries):
                color = (0, 255, 0)  # 綠色代表界內
                text = "IN"
            else:
                color = (0, 0, 255)  # 紅色代表界外
                text = "OUT"
            
            # 繪製邊界框和結果
            cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)
            cv2.putText(image, text, (int(bbox[0]), int(bbox[1])-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
    
    # 顯示結果
    cv2.imshow('Tennis Ball Detection', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 測試
process_image('tennis_test_image.jpg')

這段程式碼實現了一個簡單的系統,用來偵測網球並判斷它是否界內。它使用了 YOLOv8 來進行物件偵測,並基於網球場地的邊界來進行判斷。

主要步驟和功能解釋

  1. 載入 YOLO 模型

    model = YOLO('best.pt')
    

    這一行程式碼載入了預先訓練好的 YOLO 模型。best.pt 是訓練好的模型權重文件,你需要使用自己的模型來替換這個文件。

  2. 定義網球場邊界

    court_boundaries = {
        'left': 100,
        'right': 500,
        'top': 50,
        'bottom': 400
    }
    

    這裡定義了網球場地的邊界。leftrighttopbottom 定義了場地的左、右、上、下邊界,用於後續判斷網球是否界內。

  3. 判斷網球是否界內的函數

    def is_ball_in_bounds(ball_bbox, boundaries):
        x_center = (ball_bbox[0] + ball_bbox[2]) / 2
        y_center = (ball_bbox[1] + ball_bbox[3]) / 2
    
        if boundaries['left'] <= x_center <= boundaries['right'] and boundaries['top'] <= y_center <= boundaries['bottom']:
            return True
        else:
            return False
    

    這個函數接收網球的邊界框(ball_bbox)和場地邊界(boundaries),計算網球邊界框的中心點位置,然後判斷這個中心點是否在場地邊界內。如果在邊界內,返回 True,否則返回 False

  4. 處理圖像的主函數

    def process_image(image_path):
        image = cv2.imread(image_path)
        results = model.predict(source=image)
    

    這段程式碼讀取圖像並使用 YOLO 模型進行推論,獲取圖像中所有偵測到的物件及其邊界框。

        for result in results[0].boxes:
            bbox = result.xyxy[0].cpu().numpy()
            label = result.cls[0].cpu().numpy()
            score = result.conf[0].cpu().numpy()
    

    這裡迭代所有偵測結果,提取邊界框(bbox)、類別標籤(label)和信心分數(score)。

  5. 判斷與標記

            if label == 0:
                if is_ball_in_bounds(bbox, court_boundaries):
                    color = (0, 255, 0)
                    text = "IN"
                else:
                    color = (0, 0, 255)
                    text = "OUT"
                cv2.rectangle(image, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), color, 2)
                cv2.putText(image, text, (int(bbox[0]), int(bbox[1])-10), cv2.FONT_HERSHEY_SIMPLEX, 0.9, color, 2)
    

    這部分程式碼判斷偵測到的物件是否為網球(假設類別標籤為 0),然後根據球的位置決定是否在界內,並使用綠色(IN)或紅色(OUT)來標記結果。

  6. 顯示結果

        cv2.imshow('Tennis Ball Detection', image)
        cv2.waitKey(0)
        cv2.destroyAllWindows()
    

    最後,處理後的圖像會顯示在視窗中,展示偵測結果。

這個系統通過 YOLO 模型來偵測圖像中的網球,並基於場地邊界來判斷球是否界內,最終將結果顯示在圖像上。


上一篇
day 7 yolo v8介紹
下一篇
Day 9 Lstm候鳥行為預測
系列文
LSTM結合Yolo v8對於多隻斑馬魚行為分析29
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言